$.mobile.popup.prototype.options.history = false;
$.mobile.changePage.defaults.allowSamePageTransition = true;
// FIX IE OLD ANDROID LINK BROKEN
$.mobile.ajaxEnabled = false;
$.mobile.pushStateEnabled = false;


var __urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
var __imgRegex = /\.(?:jpe?g|gif|png|jpg)$/i;

var messageURL = "src/services/MessageService.php?key=";
var insertSignURL = "src/services/SignService.php?action=insertSign";
var deleteSignURL = "src/services/SignService.php?action=deleteSign";
var getSignURL = "src/services/SignService.php?action=getSign";
var getNotificationsURL = "src/services/NotificationService.php?action=getNotifications";
var updateNotificationViewURL = "src/services/NotificationService.php?action=updateNotificationView";
var getCountNotificationToViewURL = "src/services/NotificationService.php?action=getCountNotificationToView";

function validateEmail(email) { 
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
} 

function setMessage(key, selector) {
	$.ajax({
		type : "GET",
		url : messageURL + key,
		dataType : "JSON",
		success : function(data) {
			$(selector).html(data.value);
		}
	});
}

function getMessage(key) {
	var call = getJSON($.ajax({
		type : "GET",
		async : false,
		url : messageURL + key,
		dataType : "JSON"
	}));
	return call.value;
}

function getJSON(response){
	return JSON.parse(response.responseText);
}

function openLoading() {
	$.mobile.loading('show');
}

function closeLoading() {
	$.mobile.loading('hide');
}

function closeNavPanel() {
	$('.navigation-panel').panel().panel('close');
}
function closeNotPanel() {
	$('.notification-panel').panel().panel('close');
}
function openNotPanel() {
	$(".notification_ul").html('<li data-icon="false" onclick="closeNotPanel()" class="notification_li_close"><span class="notification_close_menu no-underline">'+getMessage("notification.close.panel")+'</span></li>');
	$(".notification-loader").html(getLoaderColored());
	$('.notification-panel:visible').panel('open');
	$.ajax({
		type : "POST",
		url : getNotificationsURL,
		data : {
			id_masker : getIdMasker()
		},
		success: function(notificationsListReponse) {
	        console.log(notificationsListReponse.value);
			
			for(var i = 0; i < notificationsListReponse.value.length; i++) {
				var notification = notificationsListReponse.value[i];
				var text = notification.text;
				var link = notification.link;
				var newNotification = (notification.view == "N") ? " new_notification" : "";
		       	$(".notification_ul").append('<li data-icon="false" onclick="goto(\''+link+'\')" class="notification_li '+newNotification+'"><span class="no-underline">'+text+'</span></li>');
		    }
		    
		    $(".notification-loader").html("");
		    cleanNotifications();
			//$(".notificationLabel").each(function() {
			//   $(this).html(" " + getMessage($(this).html()));
			//});
	   	},
		dataType : "JSON"
	});
}

function checkNotifications() {
	$.ajax({
		type : "POST",
		url : getCountNotificationToViewURL,
		data : {
			id_masker : getIdMasker()
		},
		success: function(numberNotification) {
			var lastNumber = $(".ego-notification-number").html();
	        $(".ego-notification-number").html(numberNotification.value);
	        if (lastNumber != numberNotification.value && numberNotification.value != 0) {
	        	infoNotify(getMessage("notification.new.message"));
	        }
	   	},
		dataType : "JSON"
	});
}

function cleanNotifications() {
	$.ajax({
		type : "POST",
		url : updateNotificationViewURL,
		data : {
			id_masker : getIdMasker()
		},
		success: function() {
	        checkNotifications();
	   	},
		dataType : "JSON"
	});
}

function getLoader(){
	return "<div class=\"sign-loader loading_white\"></div>";
}
function getLoaderColored(){
	return "<div class=\"sign-loader loading_colored\"></div>";
}
function getLoaderTransparent(){
	return "<div class=\"sign-loader\" style=\"width:100%;text-align:center;margin:5px\"><img class='loader-transparent' src=\"images/loader-transparent.gif\"></div>";
}



function closeSignDetail(obj) {
	var page = $(obj).closest(".ui-page").attr("id");
	$("#" + page + " #signDetail").popup("close");
}

function deleteSign(idSign, idMasker) {
	openLoading();
	
	var result = getJSON($.ajax({
		type : "POST",
		async : false,
		url : deleteSignURL,
		data : {
			id_masker : idMasker,
			id_sign : idSign
		},
		dataType : "JSON"
	})).result;
	
	// delete the li sign from the DOM
	$("#sign-"+idSign).remove();
	
	closeLoading();
	return result;
}

function insertSign(obj, idMasker, idText) {
	openLoading();
	//$(".menu_insert_sign").html(getLoaderTransparent());
	var textValue = $(obj).parent().find("#text_new_sign").val();
	if(textValue == "") {
		insertSignErrors(getMessage("sign.not.empty"));
		return false;
	}
	if(textValue.length > 250) {
		insertSignErrors(getMessage("sign.too.long"));
		return false;
	}
	var result = getJSON($.ajax({
		type : "POST",
		async : false,
		url : insertSignURL,
		data : {
			id_masker : idMasker,
			text : textValue
		},
		dataType : "JSON"
	})).result;
	$('.insert-sign-panel').panel().panel('close');
	$(obj).parent().find("#text_new_sign").val("");
	setColorCounter(250,".signCharacters");
	//$(".menu_insert_sign").html(getMessage("sign.insert.new.sign"));
	closeLoading();
	// goto my sign list
	loadSigns("mineSigns", "mine", false, idMasker);
	window.location.href = "home.php#mine";
	return result;
}

function insertSignErrors(message) {
	$('.errorPopup #errorMessage').html(message);
		closeLoading();
		$(".errorPopup").popup();
		$(".errorPopup").popup('open');
		return false;
}

function getIdMasker() {
	return $("#profile_basic_info").attr("id_masker");
}
function getNameMasker() {
	return $("#profile_basic_info").attr("name_masker");
}

function createSign(sign) {
	var code ="";
	var backgroundColor = colorfeel(sign.colorfeel_red,sign.colorfeel_green,sign.colorfeel_blue);
	var totalReplies = Number(sign.total_replies);
	var totalFeels = Number(sign.colorfeel_red) + Number(sign.colorfeel_green) + Number(sign.colorfeel_blue);
	code += '<li id="sign-'+sign.id+'" class="sign" name_masker="'+sign.name_masker+'" id_sign="'+sign.id+'" red="'+sign.colorfeel_red+'" green="'+sign.colorfeel_green+'" blue="'+sign.colorfeel_blue+'">';
	code += '	<div class="sign-header">';
	code += '		<div class="sign-header-icon"><div class="_icon sign_icon_sign"></div></div>';
	code += '		<div class="sign-header-signer">'+sign.name_masker+'</div>';
	code += '		<div class="sign-header-date"><div class="sign_date">'+sign.insert_date+'</div></div>';
	code += '	</div>';
	code += '	<div class="sign-message">'+parseURLS(sign.text)+'</div>';
	code += '	<div class="sign-footer" style="background-color:'+backgroundColor+'">';
	code += '		<div class="sign-footer-bar"></div>';
	code += '		<div class="sign-footer-number"><div class="_icon love_full_icon" style="float:left"></div><div class="sign-footer-number-total" style="margin:1px;float:right">'+totalFeels+'</div></div>';
	code += '		<div class="sign-footer-replies"><div class="_icon reply_icon" style="float:left"></div><div class="footer-total-replies-number" style="margin:1px;float:right">'+totalReplies+'</div></div>';
	code += '	</div>';
	code += '</li>';
	return code;
}

function createQuestion(question) {
	var code ="";
	var text_answer = "";
	if (question.text_answer == "" || question.text_answer == null) {
		text_answer = "<div class='question-message-no-answer'>"+getMessage("questions.question.no.answer")+"</div>";
	} else {
		text_answer = parseURLS(question.text_answer);
	}
	code += '<li class="question-li-element" idquestion="'+question.id+'">';
	code += '	<div class="question-header">';
	code += '		<div class="question-header-icon"><div class="_icon question_icon"></div></div>';
	code += '		<div class="question-header-signer">'+question.masker_name+'</div>';
	code += '		<div class="question-header-date"><div style="float:left;margin-top:4px;margin-right:3px">'+question.insert_date+'</div><div class="_icon time_icon" style="float:right"></div></div>';
	code += '	</div>';
	code += '	<div class="question-message">'+parseURLS(question.text)+'</div>';
	code += '	<div class="question-message-answer">'+text_answer+'</div>';
	code += '	<div class="question-footer">';
	code += '	</div>';
	code += '</li>';
	return code;
}

function colorfeel(red, green, blue){
	var red = Number(red);
	var green = Number(green);
	var blue = Number(blue);
	
	var array = [red,green,blue];
	var maxValueInArray = Math.max.apply(Math, array);
	
	var per = 255 / maxValueInArray;
	
	if(red != 0) {
		red = (red * per) ;
	}
	if(green != 0) {
		green = (green * per) ;
	}
	if(blue != 0) {
		blue = (blue * per) ;
	}
	
	var hexRed = getHexNum(red);
	var hexGreen = getHexNum(green);
	var hexBlue = getHexNum(blue);
	
	var hex = "#"+hexRed+""+hexGreen+""+hexBlue;
	if(hex == "#000000") {
		hex = "#DCDCDC";
	}
	return hex;
}

function getHexNum(num){
	
	num = (Math.round(num)).toString(16);
	if (num.length == 1) {
		num = "0" + num;
	}
	return num;
}

function countQuestionCharacters(obj) {
	var textValue = obj.value;
	var value = Number(500 - textValue.length);
	setColorCounter(value,".questionCharacters");
}

function countSignCharacters(obj) {
	var textValue = obj.value;
	var value = Number(250 - textValue.length);
	setColorCounter(value,".signCharacters");
}

function setColorCounter(value, classTarget){
	if (value < 0) {
		$(classTarget).css("color","red");
	} else {
		$(classTarget).css("color","grey");
	}
	$(classTarget).html(value);
}



function parseURLS($string){
    var media = '';
    var text =  $string.replace(__urlRegex,function(match){
         
            __imgRegex.lastIndex=0;
			var name = "link";
            if(__imgRegex.test(match)){
				var name = "image";
                media += '<img src="'+match+'" class="sign_image" />';
            }
            
			/*
            var length = 15;
			var name = match.replace(/^.*\/|\.[^.]*$/g, '');
			if(name.length > length) {
				name = name.substring(0, length) + "...";
			}
			*/
            return '<a href="'+match+'" target="_blank">'+name+'</a>';
            
        }
    );
    return text + '<div class="media-gallery" style="clear:both">' + media + '</div>';
}


// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

function goto(where) {
		window.location.href = where;
}


function insertReplySign(obj, idMasker) {
	var idSignFather = $(obj).closest(".signDetail").attr("id_sign");
	openLoading();
	var textValue = $(obj).parent().find(".reply-sign").val();
	if(textValue == "") {
		insertSignErrors(getMessage("sign.not.empty"));
		return false;
	}
	if(textValue.length > 250) {
		insertSignErrors(getMessage("sign.too.long"));
		return false;
	}
	var result = getJSON($.ajax({
		type : "POST",
		async : false,
		url : insertSignURL,
		data : {
			id_masker : idMasker,
			id_sign_father : idSignFather,
			text : textValue
		},
		dataType : "JSON"
	})).result;

	$(obj).parent().find(".reply-sign").val("");
	setColorCounter(250,".signCharacters");
	
	$(".sign-detail-reply").hide();
	$(".sign-detail-replies").hide();
	
	closeLoading();
	return result;
}

function hasWhiteSpace(s) {
	return s.indexOf(' ') >= 0;
}

function insertReplySignDetailLarge(obj) {
	var idSignFather = $(".menu_insert_reply").attr("id_sign_father");
	openLoading();
	var textValue = $(obj).parent().find(".reply-sign").val();
	if(textValue == "") {
		insertSignErrors(getMessage("sign.not.empty"));
		return false;
	}
	if(textValue.length > 250) {
		insertSignErrors(getMessage("sign.too.long"));
		return false;
	}
	var result = getJSON($.ajax({
		type : "POST",
		async : false,
		url : insertSignURL,
		data : {
			id_masker : getIdMasker(),
			id_sign_father : idSignFather,
			text : textValue
		},
		dataType : "JSON",
		success : function(){
			$("#sign-" + idSignFather + " .footer-total-replies-number").html(
				Number($("#sign-"+idSignFather+" .footer-total-replies-number").html()) + 1);
		}
	})).result;

	$(obj).parent().find(".reply-sign").val("");
	setColorCounter(250,".signCharacters");
	loadReplies();
	closeLoading();
	return result;
}

function infoNotify(message) {
	notif({
		type: "info",
		msg: message,
		width: "all",
		position: "center",
		opacity: 0.8,
		height: 40,
	});
}
